package com.yiyun.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yiyun.blog.dao.mapper.ArticleMapper;
import com.yiyun.blog.dao.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author Bao
 * @create 2022-05-09-10:19
 */
@Component
public class ThreadService {

    // 希望此操作在线程池执行 不会影响原有的主线程
    @Async("taskExecutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {

        int viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCounts + 1);
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Article::getId,article.getId());
        // 设置一个 为了在多线程环境下 线程安全：乐观锁，改之前再次确认这个值 没被其他抢先修改
        updateWrapper.eq(Article::getViewCounts,viewCounts);
        // update article set view_count = 100 where view_count = 99 and id = 11
        articleMapper.update(articleUpdate, updateWrapper);
    }

    @Async("taskExecutor")
    public void updateArticleComment(ArticleMapper articleMapper,Long articleId) {

        Article article = articleMapper.selectById(articleId);
        Integer commentCounts = article.getCommentCounts();
        Article articleUpdate = new Article();
        articleUpdate.setCommentCounts(commentCounts + 1);
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Article::getId, articleId);
        // 设置一个 为了在多线程环境下 线程安全：乐观锁，改之前再次确认这个值 没被其他抢先修改
        updateWrapper.eq(Article::getCommentCounts, commentCounts);
        // update article set view_count = 100 where view_count = 99 and id = 11
        articleMapper.update(articleUpdate, updateWrapper);
    }

}
